package com.lagou.edu.service.impl;

import com.lagou.edu.entity.AuthCode;
import com.lagou.edu.mapper.ICodeMapper;
import com.lagou.edu.service.ICodeService;
import com.lagou.edu.service.IEmailService;
import com.lagou.edu.utils.VerificationCodeUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 *
 * @Classname ICodeServerImpl
 * @Date 2021/5/30 17:26
 * @Author ch'ien
 */
@Service
@RefreshScope
public class ICodeServerImpl implements ICodeService {

    @Reference
    private IEmailService emailService;

    @Autowired
    private ICodeMapper codeMapper;

    @Value("${test.msg}")
    private String testMsg;

    @Override
    public Boolean create(String email) {
        if (StringUtils.isEmpty(email)){
            return false;
        }
        String code = VerificationCodeUtils.getrandom();
        if (StringUtils.isEmpty(code)){
            return false;
        }
        LocalDateTime now = LocalDateTime.now();
        AuthCode authCode = new AuthCode();
        authCode.setEmail(email)
                .setCode(code)
                .setCreatetime(now)
                .setExpiretime(now.plusMinutes(10));

        int save = codeMapper.save(authCode);
        if (save == 0){
            return false;
        }
        return emailService.send(email,code);
    }

    @Override
    public int validate(String email, String code) {
        LocalDateTime now = LocalDateTime.now();
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(code)){
            return 1;
        }

        AuthCode authCode = codeMapper.getOneByCondition(email);
        if (authCode == null){
            return 1;
        }
        if (authCode.getExpiretime().isBefore(now)){
            return 2;
        }
        if (Objects.equals(authCode.getCode(), code)){
            return 0;
        }

        return 1;
    }

    @Override
    public String testMsg() {
        return testMsg;
    }
}
